package com.twetec.cms.adapter.pc.backend.controller.website;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twetec.cms.adapter.pc.backend.annotion.SitePermission;
import com.twetec.cms.adapter.pc.backend.response.R;
import com.twetec.cms.adapter.pc.backend.response.ResultCodeMsgEnum;
import com.twetec.cms.common.constant.CmsSiteTemplatePermissionEnum;
import com.twetec.cms.model.po.user.UserPO;
import com.twetec.cms.model.vo.website.ArticleModelPageListVO;
import com.twetec.cms.model.vo.website.ArticleModelVO;
import com.twetec.cms.service.ucenter.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.website.ArticleModelPO;
import com.twetec.cms.model.vo.website.ArticleModelItemVO;
import com.twetec.cms.service.website.ArticleModelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "文章模型管理")
@RestController
@RequestMapping("/website/article-model")
public class ArticleModelController {

    @Autowired
    ArticleModelService articleModelService;

    @Autowired
    UserService userService;

    private static final String CREATE = "article-model:create";
    private static final String BATCH_REMOVE = "article-model:delete-by-ids";
    private static final String REMOVE = "article-model:delete-by-id";
    private static final String EDIT = "article-model:update-by-id";
    private static final String DETAIL = "article-model:get-by-id";
    private static final String PAGE = "article-model:page-search-list";


    @SitePermission({CREATE})
    @ApiOperation(value = "新增模型", notes = "新增模型")
    @PostMapping("/create")
    public R create(@ApiParam(value = "站点id", required = true, example = "123456789") @RequestParam(required = true) Long siteId,
                    @ApiParam(value = "模型名称", required = true, example = "模型1") @RequestParam(required = true) String name,
                    @ApiParam(value = "自定义扩展字段", required = false, example = "[{fieldCode:test_1,fieldAliase:test_122,inputType:text,fieldName:test_122,isRequired:false,isSearch:false,defaultValue:test_122,maxlength:255,description:test_122,check:true,isExtend:true,id:1632289118936,sort:0}]") @RequestParam(required = false) String extendFieldList,
                    @RequestAttribute("userId") Long userId) {
        if (siteId == null || !ValidateUtil.Number(siteId) || siteId <= 0) return R.failureRequestParam().msg("站点id不能为空");
        if (StringUtils.isEmpty(name)) return R.failureRequestParam().msg("模型名称不能为空");

        // TODO:: 打包时userId要注释
//        Long userId = 1371387567439171585L;

        ArticleModelPO articleModelPO = new ArticleModelPO();
        articleModelPO.setSiteId(siteId);
        articleModelPO.setName(name);
        articleModelPO.setCreatorId(userId);
        articleModelPO.setModifierId(userId);
        if (StringUtils.isNotEmpty(extendFieldList)) articleModelPO.setExtendFieldList(extendFieldList);
        boolean result = articleModelService.save(articleModelPO);

        if (result) return R.success();
        return R.failure();
    }

    @SitePermission({PAGE})
    @ApiOperation(value = "模型分页搜索列表", notes = "模型分页搜索列表")
    @GetMapping("/page-search-list")
    public R<ArticleModelPageListVO> pageSearchList(@ApiParam(value = "站点id", required = true, example = "123456789") @RequestParam(required = false) Long siteId,
                            @ApiParam(value = "模型名称", required = false, example = "模型1") @RequestParam(required = false) String name,
                            @ApiParam(value = "页码", required = true, example = "1") @RequestParam(required = false) Integer page,
                            @ApiParam(value = "页条目数", required = true, example = "10") @RequestParam(required = false) Integer limit,
                            @ApiParam(value = "更新人", required = false, example = "张三") @RequestParam(required = false) String modifierName,
                            @ApiParam(value = "更新时间开始（10位时间戳）", required = false, example = "12312312313") @RequestParam(required = false) Date gmtModifiedStart,
                            @ApiParam(value = "更新时间结束（10位时间戳）", required = false, example = "12313212313") @RequestParam(required = false) Date gmtModifiedEnd) {

        if (siteId == null || !ValidateUtil.Number(siteId) || siteId <= 0) return R.failureRequestParam().msg("站点id为空或格式不正确");
        if (page == null || !ValidateUtil.Number(page) || page <= 0) return R.failureRequestParam().msg("页码为空或格式不正确");
        if (limit == null || !ValidateUtil.Number(limit) || limit <= 0) return R.failureRequestParam().msg("页条目数为空或格式不正确");

        // 返回给前端的数据
        ArticleModelPageListVO articleModelPageListVO = new ArticleModelPageListVO();


        QueryWrapper<ArticleModelPO> articleModelPOQueryWrapper = new QueryWrapper<>();
        // 添加站点
        articleModelPOQueryWrapper.eq("SITE_ID", siteId);
        // 添加模型名称
        if (StringUtils.isNotEmpty(name)) articleModelPOQueryWrapper.like("NAME", name);
        // 根据更新人name查询更新人id
        List<UserPO> userPOList = null;
        if (StringUtils.isNotEmpty(modifierName)) {
            QueryWrapper<UserPO> userWrapper = new QueryWrapper<>();
            // userPOQueryWrapper1.select("ID");
            userWrapper.like("NAME", modifierName);
            userPOList = userService.list(userWrapper);
        }
        // 更新人ID
        if (userPOList != null && userPOList.size() > 0) {
            ArrayList<Long> userIdList = new ArrayList<>();
            for (UserPO userPO : userPOList) {
                userIdList.add(userPO.getId());
            }
            articleModelPOQueryWrapper.in("MODIFIER_ID", userIdList);
        }

        // 当更新人id查询结果为空，但是传入的更新人姓名不为空的时候，表示表中没有对应的操作人，直接返回空集合
        if ((userPOList == null || userPOList.size() == 0) && StringUtils.isNotEmpty(modifierName)) {
            articleModelPageListVO.setPage(page);
            articleModelPageListVO.setLimit(limit);
            articleModelPageListVO.setTotal(0);
            articleModelPageListVO.setList(new ArrayList<>());
            return R.success().data(articleModelPageListVO);
        }

        // 添加更新时间
        if (gmtModifiedStart != null) articleModelPOQueryWrapper.ge("GMT_MODIFIED", gmtModifiedStart);
        if (gmtModifiedEnd != null) articleModelPOQueryWrapper.le("GMT_MODIFIED", gmtModifiedEnd);
        // 根据更新时间倒序排列
        articleModelPOQueryWrapper.orderByDesc("GMT_MODIFIED");

        // 开始分页查询
        Page<ArticleModelPO> articleModelPOPage = articleModelService.page(new Page<>(page, limit), articleModelPOQueryWrapper);

        // VO数据
        articleModelPageListVO.setTotal((int)articleModelPOPage.getTotal());
        articleModelPageListVO.setLimit((int)articleModelPOPage.getSize());
        articleModelPageListVO.setPage((int)articleModelPOPage.getCurrent());

        List<ArticleModelPO> records = articleModelPOPage.getRecords();
        ArrayList<ArticleModelVO> articleModelVOList = new ArrayList<>();

        // 只有查询到了数据才转换
        if (records != null && records.size() > 0) {
            for (ArticleModelPO articleModelPO : records) {
                ArticleModelVO articleModelVO = new ArticleModelVO();
                BeanUtils.copyProperties(articleModelPO, articleModelVO);
                // 更新人姓名
                UserPO userPO = userService.getById(articleModelPO.getModifierId());
                if (userPO != null) articleModelVO.setModifierName(userPO.getName());
                articleModelVOList.add(articleModelVO);
            }
        }

        articleModelPageListVO.setList(articleModelVOList);

        return R.success().data(articleModelPageListVO);
    }

    @SitePermission({REMOVE})
    @ApiOperation(value = "根据id删除模型", notes = "根据id删除模型")
    @DeleteMapping("/delete-by-id")
    public R deleteById(@ApiParam(value = "模型id", required = true, example = "1440511185542696962") @RequestParam(required = false) Long id,
                        @RequestAttribute("userId") Long userId) {

        // 校验id
        if (id == null || !ValidateUtil.Number(id) )  return R.failureRequestParam().msg("id输入有误");

        // TODO:: 打包时userId要注释
//        Long userId = 1371387567439171585L;

        Boolean result = articleModelService.deleteById(id, userId);

        if (result) return R.success().msg("删除模型成功");
        return R.failure().msg("删除模型失败");
    }

    @SitePermission({BATCH_REMOVE})
    @ApiOperation(value = "批量删除模型", notes = "批量删除模型")
    @DeleteMapping("/delete-by-ids")
    public R deleteByIds(@ApiParam(value = "模型id的集合，字符串类型，用英文逗号隔开", required = true, example = "1440511185542696962,1440511185542696963") @RequestParam(required = false) String ids,
                         @RequestAttribute("userId") Long userId) {

        // 校验id

        if (ids == null || StringUtils.isEmpty(ids))  return R.failureRequestParam().msg("请指定要删除的模型id");

        // TODO:: 打包时userId要注释
//        Long userId = 1371387567439171585L;

        // 对ids进行分割
        String[] idSplit = ids.split(",");
        // 返回给前端的id是Long类型的 所以创建一个可以存放id为Long类型的数组-->idList
        ArrayList<Long> idList = new ArrayList<>();
        // 遍历idSplit 传进来的模型id的集合是字符串类型 所以先用String遍历 然后再转成Long类型的
        for (String idString : idSplit) {
            Long id = Long.valueOf(idString);
            idList.add(id);
        }

        Boolean result = articleModelService.deleteByIds(idList, userId);

        if (result) return R.success().msg("批量删除模型成功");
        return R.failure().msg("批量删除模型失败");
    }

    @SitePermission({DETAIL})
    @ApiOperation(value = "根据id获取文章模型", notes = "根据id获取文章模型")
    @GetMapping("/get-by-id")
    public R<ArticleModelItemVO> getById(@ApiParam(value = "模型id", required = true, example = "1440511185542696962") @RequestParam(required = false) Long id) {

        // 校验id
        if (id == null || !ValidateUtil.Number(id) || id <= 0) return R.failureRequestParam().msg("文章模型输入有误");

        // 查询
        QueryWrapper<ArticleModelPO> articleModelPOQueryWrapper = new QueryWrapper<>();
        articleModelPOQueryWrapper.eq("ID", id);
        ArticleModelPO articleModelPO = articleModelService.getOne(articleModelPOQueryWrapper);
        // 如果没有查询到就提示数据不存在
        if (articleModelPO == null) return R.resultCodeMsg(ResultCodeMsgEnum.DATA_NOT_EXIST);

        // 要返回的VO
        ArticleModelItemVO articleModelItemVO = new ArticleModelItemVO();
        // 如果查到的PO不为null 就赋值属性给VO
        if (articleModelPO != null) {
            BeanUtils.copyProperties(articleModelPO, articleModelItemVO);
            return R.success().data(articleModelItemVO);
        }
        return R.failure().msg("当前模型不存在");
    }

    @SitePermission({EDIT})
    @ApiOperation(value = "根据模型id更新文章模型", notes = "根据模型id更新文章模型")
    @PutMapping("/update-by-id")
    public R updateById(@ApiParam(value = "文章模型id", required = true, example = "1440511185542696962") @RequestParam(required = false) Long id,
                        @ApiParam(value = "模型名称", required = false, example = "文章模型1") @RequestParam(required = false) String name,
                        @ApiParam(value = "扩展字段", required = false, example = "[{fieldCode:test_1,fieldAliase:test_122,inputType:text,fieldName:test_122,isRequired:false,isSearch:false,defaultValue:test_122,maxlength:255,description:test_122,check:true,isExtend:true,id:1632289118936,sort:0}]") @RequestParam(required = false) String extendFieldList,
                        @RequestAttribute("userId") Long userId) {

        // 校验id
        if (id == null || !ValidateUtil.Number(id) || id <= 0) return R.failureRequestParam().msg("文章模型输入有误");

        // TODO:: 打包时userId要注释
//        Long userId = 1371387567439171585L;

        // 执行更新
        ArticleModelPO articleModelPO = new ArticleModelPO();
        articleModelPO.setModifierId(userId);
        articleModelPO.setId(id);
        articleModelPO.setName(name);
        articleModelPO.setExtendFieldList(extendFieldList);
        boolean result = articleModelService.updateById(articleModelPO);

        if (result) return R.success().msg("操作成功");
        return R.failure().msg("操作失败");
    }
}
